import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../common/utils.dart';

import '../common/routes.dart';
import '../model/community_video_model.dart';

class VideoRankListView extends StatefulWidget {
  final String rankType;

  const VideoRankListView({super.key, required this.rankType});

  @override
  State<VideoRankListView> createState() => _VideoRankListViewState();
}

class _VideoRankListViewState extends State<VideoRankListView> with AutomaticKeepAliveClientMixin {
  final ScrollController _scrollController = ScrollController();
  final List<IssueList> _videoList = [];
  bool _isLoadingMore = false;
  bool _isLoadingData = true;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_isLoadingMore) {
        _loadMore();
      }
    });

    loadData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _loadMore() async {
    setState(() {
      _isLoadingMore = true;
    });
    await loadData();
  }

  loadData() async {
    Dio dio = Dio();
    var params = {
      "strategy": widget.rankType,
      "start": _videoList.length,
      "num": 20,
    };
    final url = "https://baobab.kaiyanapp.com/api/v4/rankList/videos";
    final response = await dio.get(url, queryParameters: params);
    var model = CommunityVideoModel.fromJson(response.data);
    setState(() {
      _isLoadingData = false;
      _isLoadingMore = false;
      if (model.count! > 0) {
        _videoList.addAll(model.itemList ?? []);
      } else {
        _hasMore = false;
      }
    });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  Widget build(BuildContext context) {
    super.build(context);
    if (_isLoadingData) {
      return Center(
        child: Container(
          margin: const EdgeInsets.all(8.0),
          width: 64.0,
          height: 64.0,
          child: const CircularProgressIndicator(),
        ),
      );
    }
    return ListView.builder(
      controller: _scrollController,
      itemCount: _videoList.length + 1,
      itemBuilder: (context, index) {
        if (index == _videoList.length) {
          if (_isLoadingMore) {
            // Show loading indicator
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: CircularProgressIndicator()),
            );
          } else if (!_hasMore) {
            // No more data
            return Padding(
              padding: const EdgeInsets.all(8.0),
              child: Center(child: Text('没有更多数据了')),
            );
          } else {
            return SizedBox.shrink();
          }
        }

        final item = _videoList[index];

        return GestureDetector(
          child: Container(
            color: Colors.white,
            margin: EdgeInsets.symmetric(vertical: 5, horizontal: 10),
            child: Column(
              children: [
                Stack(
                  children: [
                    ClipRRect(
                      borderRadius: BorderRadius.circular(8),
                      child: CachedNetworkImage(
                        width: double.infinity,
                        height: 200,
                        fadeInDuration: const Duration(seconds: 0),
                        fadeOutDuration: const Duration(seconds: 0),
                        fit: BoxFit.cover,
                        imageUrl: item.data?.cover?.feed ?? '',
                        placeholder: (context, url) {
                          return Image.asset(
                            "assets/images/placeholder.png",
                            fit: BoxFit.cover,
                          );
                        },
                      ),
                    ),
                    Positioned(
                      right: 10,
                      bottom: 10,
                      child: Container(
                        padding: EdgeInsets.all(2),
                        decoration: BoxDecoration(
                          border: Border.all(width: 0.5, color: Colors.white),
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: Text(
                          formatSeconds(item.data?.duration ?? 0),
                          style: TextStyle(fontFamily: 'dinpro', color: Colors.white, fontSize: 10, shadows: [
                            Shadow(
                              offset: Offset(1.0, 1.0),
                              blurRadius: 1.0,
                              color: Colors.grey,
                            ),
                          ]),
                        ),
                      ),
                    ),
                  ],
                ),
                Row(
                  children: [
                    SizedBox(
                      width: 45,
                      height: 45,
                      child: Stack(
                        children: [
                          ClipRRect(
                            borderRadius: BorderRadius.circular(20),
                            child: CachedNetworkImage(
                              fit: BoxFit.cover,
                              fadeInDuration: const Duration(milliseconds: 100),
                              fadeOutDuration: const Duration(seconds: 0),
                              imageUrl: item.data?.author?.icon ?? '',
                              width: 40,
                              height: 40,
                            ),
                          ),
                          Positioned(
                            right: 4,
                            bottom: 6,
                            width: 10,
                            height: 10,
                            child: Image.asset(
                              'assets/images/icon_author.png',
                              fit: BoxFit.cover,
                            ),
                          )
                        ],
                      ),
                    ),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.symmetric(horizontal: 5, vertical: 10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              item.data?.title ?? '',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: Colors.black.withOpacity(.72), fontSize: 14, fontWeight: FontWeight.bold),
                            ),
                            Text(
                              '${item.data?.author?.name ?? ''} / #${item.data?.category ?? ''}',
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.black.withOpacity(.4),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
          onTap: () {
            Get.toNamed(Routes.VIDEO_DETAIL, arguments: {"id": item.data?.id, "playUrl": item.data?.playUrl});
          },
        );
      },
    );
  }
}
